<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import request from "../../../utils/Request.js";
import { ElMessage } from "element-plus";
import store from "../../../store/index.js";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { ref } from "vue";
import router from "../../../router/index.js";

export default {
  name: "RtfEdit",
  computed: {
    store() {
      return store;
    },
  },
  components: { Editor, Toolbar },
  props: {
    id: String,
    index: Number,
  },
  watch: {
    valueHtml() {
      // 编辑器创建会触发一次
      if (this.first) this.first = false;
      else if (!store.state.planeTabIsModified[this.index]) {
        if (!this.firstContent)
          store.state.planeTabIsModified[this.index] = true;
        else this.firstContent = false;
      }
    },
  },
  setup(props) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref("");

    const toolbarConfig = {};
    const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
      editorRef.value.on("save", saveContent);
    };

    // 上传图片配置
    editorConfig.MENU_CONF["uploadImage"] = {
      // server: '/api/project/doc/upload/image',
      // form-data fieldName ，默认值 'wangeditor-uploaded-image'
      fieldName: "image",

      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 2 * 1024 * 1024,

      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 1,

      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["image/*"],

      // 将 meta 拼接到 url 参数中，默认 false
      metaWithUrl: false,

      // 跨域是否传递 cookie ，默认为 false
      withCredentials: false,

      // 超时时间，默认为 10 秒
      timeout: 10 * 1000,
      // 自定义插入图片
      // 自定义上传
      async customUpload(file, insertFn) {
        let formdata = new FormData();
        formdata.append("image", file);
        request({
          url: "/api/project/doc/upload/image",
          method: "post",
          data: formdata,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }).then(({ data }) => {
          // console.log(data)
          if (data.code === 0) {
            insertFn(data.data.url, file.name, data.data.url);
          } else {
            console.log(data);
            ElMessage.error(data.msg);
          }
        });
        // insertFn(url, alt, href)
      },
    };

    toolbarConfig.insertKeys = {
      index: 32, // 插入的位置，基于当前的 toolbarKeys
      keys: ["|", "SaveButtonMenu"],
    };

    const saveContent = () => {
      // console.log(router)
      // const toolbar = DomEditor.getToolbar(editorRef.value)
      // const curToolbarConfig = toolbar.getConfig()
      // console.log(curToolbarConfig.toolbarKeys) // 当前菜单排序和分组
      if (store.state.planeTabIsModified[props.index])
        request({
          url: "/api/project/rtf/content/save",
          method: "post",
          data: {
            projectId: router.currentRoute.value.params.projectId,
            id: props.id,
            content: valueHtml.value,
          },
        }).then(({ data }) => {
          if (data.code === 0) {
            ElMessage.success("保存成功");
            store.state.planeTabIsModified[props.index] = false;
          } else {
            ElMessage.error(data.msg);
          }
        });
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      saveContent,
    };
  },
  data() {
    return {
      first: true,
      firstContent: false,
    };
  },
  methods: {
    ctrlSave(event) {
      if (event.ctrlKey && event.key === "s") {
        event.preventDefault();
        this.saveContent();
      }
    },
  },
  created() {
    request({
      url: "/api/project/rtf/content",
      method: "post",
      data: {
        projectId: this.$route.params.projectId,
        id: this.id,
      },
    }).then(({ data }) => {
      if (data.code === 0) {
        this.valueHtml = data.data == null ? "" : data.data;
        if (this.valueHtml !== "") this.firstContent = true;
      } else {
        ElMessage.error(data.msg);
      }
    });
  },
};
</script>

<template>
  <div style="border: 1px solid #ccc" v-on:keydown="ctrlSave">
    <Toolbar
      style="border-bottom: 1px solid rgba(204, 204, 204, 0.3)"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: calc(100vh - 220px); overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
  <br />
  <!-- <el-button style="position: absolute; left: 90%; top: 94%"
             type="primary"
             size="large"
             @click="saveContent"
  >
    保存
  </el-button> -->
</template>

<style>
</style>